﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace translator.Command
{
    public class ReadHintFromDictCommand : ICommand
    {
        MainWindow mainWindow;
        public ReadHintFromDictCommand(MainWindow mainWindow)
        {
            this.mainWindow = mainWindow;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            if (!File.Exists(Properties.Settings.Default.DictionaryPath) || mainWindow.model.HintLst == null) { return false; }
            return true;
        }

        public void Execute(object parameter)
        {
            //mainWindow.Log(Properties.Settings.Default["DictionaryPath"] as string);
            ReadHintFromDictFile(Properties.Settings.Default.DictionaryPath);
        }
        public void ReadHintFromDictFile(string dictpath)
        {

            mainWindow.Log("ReadHintFromDictFile");
            //dictpath = @"C:\Users\17395\Desktop\游戏开发\englishwords\newdict_english_chinese.db.dictionary";   //测试
            mainWindow.Log("dictpath:" + dictpath);
            var conn = new SQLiteConnection(dictpath);
            conn.ConnectionString = "Data Source=" + dictpath;
            try
            {
                conn.Open();
            }
            catch (Exception e)
            {
                mainWindow.Log("Dictionary connect failed,Exception:" + e.StackTrace);
            }
            var comd = conn.CreateCommand();
            comd.CommandText = @"select TranslatedHint from hint where OriginalWord = @OriginalWord";
            var P_OriginalWord = comd.CreateParameter();
            P_OriginalWord.ParameterName = "OriginalWord";
            comd.Parameters.Add(P_OriginalWord);
            try
            {
                foreach (var ht in mainWindow.model.HintLst)
                {
                    P_OriginalWord.Value = ht.OriginWord;
                    var reader = comd.ExecuteReader();
                    while (reader.Read())
                    {
                        ht.TranslatedHint = reader.GetString(0);
                        mainWindow.hintTable[ht.OriginWord] = ht.TranslatedHint;
                    }
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                mainWindow.Log("read dictionary failed,Exception:" + e.StackTrace);
            }
            comd.Dispose();
            conn.Dispose();
            mainWindow.HintTable.Items.Refresh();
        }
    }
}
